package br.com.sgo.util.hibernate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;

@Component
@ApplicationScoped
public class SessionFactoryCreator implements ComponentFactory<SessionFactory> {

	private ServiceRegistry serviceRegistry;
	private Configuration cfg;
	private SessionFactory sessionFactory;

	public SessionFactoryCreator(Configuration cfg, 
			ServiceRegistry serviceRegistry) {
		this.cfg = cfg;
		this.serviceRegistry = serviceRegistry;
	}

	@PostConstruct
	protected void create() {
		this.sessionFactory = this.cfg.buildSessionFactory(this.serviceRegistry);
	}

	@PreDestroy
	protected void destroy() {
		if (!this.sessionFactory.isClosed())
			this.sessionFactory.close();
	}

	public SessionFactory getInstance() {
		return this.sessionFactory;
	}

}
